<template>
  <div class="user-manage-container">
    <el-card class="header">
      <div>
        <el-button type="success" @click="userAdd">{{
          $t('msg.user.userAdd')
        }}</el-button>
        <el-button
          class="float-right"
          type="primary"
          @click="onImportExcelClick"
          v-permission="['importUser']"
          >{{ $t('msg.user.importExcel') }}</el-button
        >
        <el-button
          type="warning"
          class="float-right"
          @click="onExportExcelClick"
          >{{ $t('msg.user.exportExcel') }}</el-button
        >
      </div>
    </el-card>
    <el-card>
      <el-table :data="tableData" border style="width: 100%">
        <!-- 索引 -->
        <el-table-column label="#" type="index"></el-table-column>
        <!-- 姓名 -->
        <el-table-column
          :label="$t('msg.user.userName')"
          align="center"
          prop="userName"
        ></el-table-column>
        <!-- 姓名 -->
        <el-table-column
          :label="$t('msg.user.name')"
          align="center"
          prop="name"
        ></el-table-column>
        <!-- 手机号 -->
        <el-table-column
          :label="$t('msg.user.phone')"
          prop="phone"
          align="center"
        ></el-table-column>
        <el-table-column :label="$t('msg.user.role')" align="center">
          <template #default="{ row }">
            <div v-if="row.roles && row.roles.length > 0">
              <el-tag v-for="item in row.roles" :key="item.id" size="mini">
                {{ item.title }}
              </el-tag>
            </div>
            <div v-else>
              <el-tag size="mini">{{ $t('msg.user.defaultRole') }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column :label="$t('msg.user.createTime')" align="center">
          <template #default="{ row }">
            {{ $filters.dateFilter(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('msg.user.status')" align="center">
          <template #default="{ row }">
            <span :class="{ disabled: row.deleted === 1 }">{{
              $filters.statusFilter(row.deleted)
            }}</span>
          </template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column
          :label="$t('msg.btn.action')"
          fixed="right"
          align="center"
          width="420px"
        >
          <template #default="{ row }">
            <el-button type="info" size="mini" @click="onShowClick(row.id)">{{
              $t('msg.btn.show')
            }}</el-button>
            <el-button
              type="success"
              size="mini"
              @click="onDetailClick(row)"
              v-permission="['distributeRole']"
              >{{ $t('msg.btn.detail') }}</el-button
            >
            <el-button
              type="primary"
              size="mini"
              @click="onShowRoleClick(row)"
              v-permission="['distributeRole']"
              >{{ $t('msg.user.showRole') }}</el-button
            >
            <el-button
              type="primary"
              size="mini"
              @click="onResetPasswordClick(row)"
              v-permission="['distributeRole']"
              >{{ $t('msg.user.reset') }}</el-button
            >
            <el-button
              v-if="row.deleted === 0"
              type="danger"
              size="mini"
              @click="onDisableClick(row)"
              v-permission="['removeUser']"
              >{{ $t('msg.user.disable') }}</el-button
            >
            <el-button
              v-else
              type="warning"
              size="mini"
              @click="onEnableClick(row)"
              v-permission="['removeUser']"
              >{{ $t('msg.user.enable') }}</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-size="size"
        :total="total"
        :page-sizes="[10, 20]"
        layout="total,sizes,prev,pager,next,jumper"
      ></el-pagination>
    </el-card>
    <export-excel v-model="exportToExcelVisible"></export-excel>
    <roles-dialog
      v-model="roleDialogVisible"
      :userId="selectUserId"
      @updateRole="getListData"
    ></roles-dialog>
  </div>
</template>

<script setup>
import { ref, onActivated, watch } from 'vue'
import {
  getUserManageList,
  disableUser,
  enableUser,
  resetPassword
} from '@/api/user-manage'
import { watchSwitchLang } from '@/utils/i18n'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useI18n } from 'vue-i18n'
import ExportExcel from './components/Export2Excel.vue'
import RolesDialog from './components/Roles.vue'

const tableData = ref([])
const total = ref(0)
const page = ref(1)
const size = ref(10)
const getListData = async () => {
  const result = await getUserManageList({
    page: page.value,
    size: size.value
  })
  tableData.value = result.items
  total.value = result.total
}
getListData()
watchSwitchLang(getListData)

const onDetailClick = (row) => {
  router.push(`/user/detail/${row.id}`)
}
const handleSizeChange = (currentSize) => {
  size.value = currentSize
  getListData()
}
const handleCurrentChange = (currentPage) => {
  page.value = currentPage
  getListData()
}

// excel导入
const router = useRouter()
const onImportExcelClick = () => {
  router.push('/user/import')
}
onActivated(getListData)
const i18n = useI18n()
const onDisableClick = (row) => {
  ElMessageBox.confirm(
    i18n.t('msg.user.dialogDisabledTitle1') +
      row.userName +
      i18n.t('msg.user.dialogDisabledTitle2'),
    {
      type: 'warning'
    }
  ).then(async () => {
    await disableUser(row.id)
    ElMessage.success(i18n.t('msg.user.disableSuccess'))
    getListData()
  })
}
const onEnableClick = (row) => {
  ElMessageBox.confirm(
    i18n.t('msg.user.dialogEnabledTitle1') +
      row.userName +
      i18n.t('msg.user.dialogEnabledTitle2'),
    {
      type: 'warning'
    }
  ).then(async () => {
    await enableUser(row.id)
    ElMessage.success(i18n.t('msg.user.enableSuccess'))
    getListData()
  })
}

const onResetPasswordClick = (row) => {
  ElMessageBox.confirm(
    i18n.t('msg.user.dialogResetTitle1') +
      row.userName +
      i18n.t('msg.user.dialogResetTitle2'),
    {
      type: 'warning'
    }
  ).then(async () => {
    await resetPassword(row.id)
    ElMessage.success(i18n.t('msg.user.resetPasswordSuccess'))
    getListData()
  })
}

// 导出
const exportToExcelVisible = ref(false)

const roleDialogVisible = ref(false)

const selectUserId = ref('')
watch(roleDialogVisible, (val) => {
  if (!val) selectUserId.value = ''
})

const onShowRoleClick = (row) => {
  roleDialogVisible.value = true
  selectUserId.value = row.id
}

const onExportExcelClick = () => {
  exportToExcelVisible.value = true
}
// 查看用户详情
const onShowClick = (id) => {
  router.push(`/user/info/${id}`)
}

const userAdd = () => {
  router.push('/user/add')
}
</script>

<style lang="scss" scoped>
.user-manage-container {
  .header {
    margin-bottom: 22px;
    text-align: left;
    .float-right {
      float: right;
    }
  }
  .disabled {
    color: orange;
  }
  ::v-deep .avatar {
    width: 60px;
    height: 60px;
    border-radius: 50%;
  }

  ::v-deep .el-tag {
    margin-right: 6px;
  }

  .pagination {
    display: flex;
    margin-top: 20px;
    justify-content: center;
  }
}
</style>
